package com.czmh.etc.onlinepubsys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseResponse;
import com.aliyun.tea.TeaException;
import com.czmh.etc.common.core.annotation.ApiVersion;
import com.czmh.etc.common.core.utils.Base64ImageUtil;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.dto.*;
import com.czmh.etc.onlinepubsys.json.DetailJson;
import com.czmh.etc.onlinepubsys.model.SysFile;
import com.czmh.etc.onlinepubsys.request.CardRequest;
import com.czmh.etc.onlinepubsys.services.SysFileService;
import com.czmh.etc.onlinepubsys.utils.AliOCRUtil;
import com.czmh.etc.onlinepubsys.utils.JsonResultUtil;
import com.czmh.etc.onlinepubsys.utils.ResponseJsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @描述：OcrController
 * @author： Seven.
 * @创建日期：Jun 9, 2019 1:28:42 PM.
 * @版本：1.0.0
 */
@RestController
@RequestMapping("/{version}/ocr")
@Api(tags = "OCR证件识别")
@Slf4j
public class OcrController {
    public Logger logger = LoggerFactory.getLogger(OcrController.class);

    @Value("${sys.upload.imagepath}")
    private String upload_image_url;
    @Autowired
    private SysFileService sysFileService;

    private static String res_path = "res/images";

    @Value("${aliyunsdk.ocr.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyunsdk.ocr.accessKeySecret}")
    private String accessKeySecret;


    @PostMapping("/business")
    @ApiOperation("识别营业执照")
    public Object businessLicense(@RequestBody CardRequest idcardRequest) {

        BusinessLicenseDto data = new BusinessLicenseDto();
        // 上传图片
        String url = "";
        try {
            List<String> imagebase64List = new ArrayList<String>();
            imagebase64List.add(idcardRequest.getImage());
            List<String> list = this.dealUpload(imagebase64List, idcardRequest.getUser_id());
            if (CollectionUtils.isEmpty(list)) {
                return JsonResultUtil.toErrorResult("上传文件失败");
            } else {
                String path = list.get(0);
                File file = new File(System.getProperty("user.dir") + File.separator + "static" + File.separator + path);
                FileInputStream inputStream = new FileInputStream(file);
                MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(inputStream));
                url = sysFileService.saveFileToOss(idcardRequest.getUser_id(), multipartFile).getData().toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            data.setSuccess(false);
        }
        RecognizeBusinessLicenseResponse response = null;
        try {
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // 必填，您的 AccessKey ID
                    .setAccessKeyId(accessKeyId)
                    // 必填，您的 AccessKey Secret
                    .setAccessKeySecret(accessKeySecret);
            // 访问的域名
            config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
            com.aliyun.ocr_api20210707.Client client = new com.aliyun.ocr_api20210707.Client(config);
            com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest recognizeBusinessLicenseRequest = new com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest();
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            // 复制代码运行请自行打印 API 的返回值
            recognizeBusinessLicenseRequest.setUrl(url);
            //recognizeBusinessLicenseRequest.setBody(FileUtil.getInputStream("/root/third/static/res/images/45712837126651904/2022/11/27/202211272308108037.jpg"));
            response = client.recognizeBusinessLicenseWithOptions(recognizeBusinessLicenseRequest, runtime);
        } catch (TeaException error) {
            error.printStackTrace();
            data.setSuccess(false);
        } catch (Exception _error) {
            _error.printStackTrace();
            data.setSuccess(false);
        }
        log.info("识别营业执照-{}", JSON.toJSONString(response));
        if (response != null) {
            JSONObject object = JSON.parseObject(response.getBody().getData());
            object = object.getJSONObject("data");
            data.setAddress(object.getString("businessAddress"));
            data.setName(object.getString("companyName"));
            data.setPerson(object.getString("legalPerson"));
            data.setReg_num(object.getString("creditCode"));
            data.setBusiness(object.getString("businessScope"));
            data.setSuccess(true);
        } else {
            data.setSuccess(false);
        }
        data.setBusinessLicenseUrl(url);
        return ResponseJsonUtil.getDetailJson(data);
    }

    @PostMapping("/idcard")
    @ApiOperation(value = "识别身份证")
    public DetailJson<?> idcard(@RequestBody CardRequest idcardRequest) {
        JSONObject configObj = new JSONObject();
        configObj.put("side", idcardRequest.getSide());
        String config_str = configObj.toString();
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", idcardRequest.getImage());
        requestObj.put("configure", config_str);
        String bodys = requestObj.toString();
        String resultStr = AliOCRUtil.card(1, bodys);

        // 上传图片
        List<String> imagebase64List = new ArrayList<String>();
        imagebase64List.add(idcardRequest.getImage());
        List<String> urlpaths = this.dealUpload(imagebase64List, idcardRequest.getUser_id());
        if ("back".equals(idcardRequest.getSide())) {
            EtcIdcarBackDto data = JSONObject.parseObject(resultStr, EtcIdcarBackDto.class);
            data.setCardbackres_path(urlpaths.get(0));
            return ResponseJsonUtil.getDetailJson(data);
        } else {
            EtcIdcarFaceDto data = JSONObject.parseObject(resultStr, EtcIdcarFaceDto.class);
            data.setCardfaceres_path(urlpaths.get(0));
            return ResponseJsonUtil.getDetailJson(data);
        }
    }

    @ApiVersion(1)
    @PostMapping("/vehicle")
    @ApiOperation(value = "识别行驶证")
    public DetailJson<?> vehicle(@RequestBody CardRequest idcardRequest) {
        JSONObject configObj = new JSONObject();
        configObj.put("side", idcardRequest.getSide());
        String config_str = configObj.toString();
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", idcardRequest.getImage());
        requestObj.put("configure", config_str);
        String bodys = requestObj.toString();
        String resultStr = AliOCRUtil.card(2, bodys);
        // 上传图片
        List<String> imagebase64List = new ArrayList<String>();
        imagebase64List.add(idcardRequest.getImage());
        List<String> urlpaths = this.dealUpload(imagebase64List, idcardRequest.getUser_id());
        if ("back".equals(idcardRequest.getSide())) {
            EtcVehiclelicenseBackDto data = JSONObject.parseObject(resultStr, EtcVehiclelicenseBackDto.class);
            data.setLelicensbackres_path(urlpaths.get(0));
            return ResponseJsonUtil.getDetailJson(data);
        } else {
            EtcVehiclelicenseFaceDto data = JSONObject.parseObject(resultStr, EtcVehiclelicenseFaceDto.class);
            data.setLicensefaceres_path(urlpaths.get(0));
            return ResponseJsonUtil.getDetailJson(data);
        }

    }

    /**
     * 上传图片
     *
     * @param imagebase64List 图片base64字符串
     * @param user_id         用户id
     * @return
     */
    private List<String> dealUpload(List<String> imagebase64List, String user_id) {
        List<String> imgFileUrls = new ArrayList<String>();
        dealBase64(imagebase64List, user_id, imgFileUrls, upload_image_url, res_path, sysFileService);
        return imgFileUrls;
    }

    static void dealBase64(List<String> imagebase64List, String user_id, List<String> imgFileUrls, String upload_image_url, String res_path, SysFileService sysFileService) {
        if (imagebase64List != null && imagebase64List.size() > 0) {
            Date now = new Date();
            String year = new SimpleDateFormat("yyyy").format(now);
            String month = new SimpleDateFormat("MM").format(now);
            String day = new SimpleDateFormat("dd").format(now);
            String oputFilepath = "", path = "";
            if (StringUtils.isNotEmpty(user_id)) {
                oputFilepath = upload_image_url + File.separator + user_id + File.separator + year + File.separator + month + File.separator + day;
                path = res_path + File.separator + user_id + File.separator + year + File.separator + month + File.separator + day;
            } else {
                oputFilepath = upload_image_url + File.separator + year + File.separator + month + File.separator + day;
                path = res_path + File.separator + year + File.separator + month + File.separator + day;
            }
            for (String imagebase64 : imagebase64List) {
                String newFileName = Base64ImageUtil.getFileName(".jpg");
                String fullFileName = oputFilepath + File.separator + newFileName;
                File outFile = new File(fullFileName);
                File parent = outFile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                File img = Base64ImageUtil.generateImage(imagebase64, outFile);
                String rpath = path + File.separator + newFileName;
                String url = rpath.replaceAll("\\\\", "/");
                imgFileUrls.add(url);
                // 保存数据库
                SysFile file = new SysFile(Sequence.getId());
                file.setFile_bytes(img.getTotalSpace());
                file.setFile_createtime(new Date());
                file.setFile_delstatus(false);
                file.setFile_path(url);
                file.setFile_createid(user_id);
                file.setFile_type("图片");
                file.setFile_notes("上传图片");
                file.setFile_ext(".jpg");
                file.setFile_name(newFileName);
                sysFileService.save(file);
            }
        }
    }
}
